package com.yxp423.ssmempl.service.impl;

import cn.hutool.cache.Cache;
import cn.hutool.cache.CacheUtil;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yxp423.ssmempl.bean.Func;
import com.yxp423.ssmempl.bean.User;
import com.yxp423.ssmempl.bean.UserRole;
import com.yxp423.ssmempl.mapper.FuncMapper;
import com.yxp423.ssmempl.mapper.UserRoleMapper;
import com.yxp423.ssmempl.service.IFuncService;
import com.yxp423.ssmempl.utils.base.AjaxResult;
import com.yxp423.ssmempl.utils.consts.ApplyConst;
import com.yxp423.ssmempl.utils.consts.UserConst;
import org.apache.catalina.security.SecurityUtil;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @Description: java类作用描述
 * @Author: yxp
 * @CreateDate: 2019-04-23 10:33
 * @Version: 1.0
 */
@Service
public class FuncServiceEmpl implements IFuncService {

	@Autowired
	FuncMapper funcMapper;
	@Autowired
	UserRoleMapper userRoleMapper;

	Cache<String, List> funcTreeCache = CacheUtil.newLRUCache(10, DateUnit.MINUTE.getMillis() * 5);

	@Override
	public AjaxResult getFirstMenu() {

		AjaxResult result = new AjaxResult();
		List<Func> firstMenu = funcMapper.getFirstMenu();
		for (Func menu : firstMenu) {
			List<Func> secondMenu = funcMapper.getSecondMenuByPid(menu.getFuncId());

		}

		if (firstMenu != null) {

			result.setSuccess(true);
			result.setData(firstMenu);
		} else {
			result.setSuccess(false);
			result.setMsg("没找到一级菜单");
		}
		return result;
	}

	@Override
	public AjaxResult getSecondMenu() {

		AjaxResult result = new AjaxResult();

		List<Func> secondMenu = funcMapper.getSecondMenu();
		if (secondMenu != null) {
			result.setSuccess(true);
			result.setData(secondMenu);

		} else {
			result.setSuccess(false);
			result.setMsg("没找到二级菜单");
		}

		return result;
	}


	public AjaxResult findTree() {

		boolean isEmpl = false;
		boolean isManager = false;
		boolean isAdmin = false;
		boolean isXzbm = false;

		User user = (User) SecurityUtils.getSubject().getPrincipal();

		List<UserRole> userRoleList = userRoleMapper.selectList(new QueryWrapper<UserRole>().eq("user_id", user.getUserId().toString()));

		for (UserRole role : userRoleList) {

			if (StrUtil.equals(role.getRoleNo(), UserConst.USER_ROLE_PROJECTMANAGE)
					|| StrUtil.equals(role.getRoleNo(), UserConst.USER_ROLE_DEPTMANAGE)) {    //项目经理或部门经理
				isManager = true;

			} else if (StrUtil.equals(role.getRoleNo(), UserConst.USER_ROLE_ADMIN)) {//超级管理

				isAdmin = true;
			} else if (StrUtil.equals(role.getRoleNo(), UserConst.USER_ROLE_XZBM)) {//行政部门

				isXzbm = true;

			} else if (StrUtil.equals(role.getRoleNo(), UserConst.USER_ROLE_EMPL)) {    //员工
				isEmpl = true;

			}

		}


		AjaxResult result = new AjaxResult();

//		if (ObjectUtil.isEmpty(funcTreeCache.get("treeCache"))) {
		//查询所有菜单
		List<Func> allMenu = funcMapper.getAllMenu();

		List<Func> firstMenu = funcMapper.selectList(new QueryWrapper<Func>().eq("func_level", "1"));
		//根节点数组
		List<Func> rootMenu = new ArrayList<>();

		try {
			for (Func menu : firstMenu) {

				//如果父节点是0，那么就是根节点（一级菜单）
//				if (menu.getPid().equals("0")) {

				if (isAdmin) {

					rootMenu.add(menu);
				} else if (isManager) {
					if (!StrUtil.equals(menu.getFuncUrl(), "/system")) {
						rootMenu.add(menu);
					}

				} else if (isXzbm) {
					if (!StrUtil.equals(menu.getFuncUrl(), "/project")) {

						rootMenu.add(menu);
					}

				} else if (isEmpl) {
					if (!StrUtil.equals(menu.getFuncUrl(), "/system")) {

						if (!StrUtil.equals(menu.getFuncUrl(), "/project")) {

							rootMenu.add(menu);
						}
					}
				}

//				}
			}
			Collections.sort(rootMenu, order());

			//为根目录设置子菜单
			for (Func menu : rootMenu) {

				//获取根节点下的所有子节点
				List<Func> childList = getChildMenu(menu, allMenu);
				menu.setChildFunc(childList);

			}

			/**
			 * 输出构建好的菜单数据。
			 *
			 */
			//            data.put("success", "true");
			//            data.put("list", rootMenu);
			//            return data;

			result.setSuccess(true);
			result.setMsg("菜单加载成功!");
			result.setData(rootMenu);

//				funcTreeCache.put("treeCache", rootMenu);
			return result;

		} catch (Exception e) {

			result.setSuccess(false);
			result.setMsg("系统出错" + e.toString());
			return result;

		}


	}


	public List<Func> getChildMenu(Func parentMenu, List<Func> allMenu) {

		//子菜单数组
		List<Func> childList = new ArrayList<>();

		// 遍历所有节点，将所有菜单的父id与传过来的根节点的id比较
		for (Func menu : allMenu) {

			//相等说明：为该根节点的子节点。
			if (menu.getPid().equals(parentMenu.getFuncId())) {


				menu.setFuncUrl(parentMenu.getFuncUrl() + menu.getFuncUrl());
				childList.add(menu);
			}

		}

//        for (Func menu : childList) {
//
//            //递归
//            menu.setChildFunc(getChildMenu(menu.getFuncId(), childList));
//
//        }  //只有两级菜单 所以不用再递归查找下级
		Collections.sort(childList, order());//排序
		if (childList.size() == 0) {

			return new ArrayList<Func>();
		}

		return childList;
	}


	/**
	 * 对菜单排序
	 */
	public Comparator<Func> order() {

		Comparator<Func> comparator = (o1, o2) -> {

			if (o1.getFuncOrder() != o2.getFuncOrder()) {

				return o1.getFuncOrder() - o2.getFuncOrder();
			}

			return 0;
		};

		return comparator;
	}


	@Override
	public AjaxResult saveFunc(Func func) {

		AjaxResult result = new AjaxResult();

		User user = (User) SecurityUtils.getSubject().getPrincipal();

		if (ObjectUtil.isNull(user)) {

			result.setSuccess(false);
			result.setMsg("请登录");
			return result;
		}

		try {
			if (ObjectUtil.isEmpty(func.getFuncId())) { //funcId为空，说明是新增菜单

				func.setCreatorId(user.getUserId().toString());

				if (funcMapper.insert(func) > 0) {

					result.setSuccess(true);
					result.setMsg("添加成功");
					funcTreeCache.clear();

				} else {

					result.setSuccess(false);
					result.setMsg("添加失败");
				}


			} else {

				Func funcOne = funcMapper.selectOne(new QueryWrapper<Func>().eq("func_id", func.getFuncId()));

				func.setUpdaterId(user.getUserId().toString());

				func.setVersion(funcOne.getVersion());
				if (ObjectUtil.isNull(funcOne)) {

					result.setSuccess(false);
					result.setMsg("数据库中没有该菜单，无法修改");
					return result;

				} else {

//					int flag = funcMapper.update(func, new QueryWrapper<Func>().eq("func_id", func.getFuncId()));

					int flag = funcMapper.updateById(func);

					if (flag > 0) {

						result.setSuccess(true);
						result.setMsg("修改成功");

						funcTreeCache.clear();

						return result;

					} else {

						result.setSuccess(false);
						result.setMsg("修改失败");
						return result;

					}


				}
			}
		} catch (Exception e) {
			result.setSuccess(false);
			result.setMsg(e.toString());
			e.printStackTrace();
		}


//        funcMapper.saveFunc(func);

		return result;
	}

	@Override
	@Transactional(rollbackFor = RuntimeException.class)
	public AjaxResult deleteFunc(Func func) {

		AjaxResult result = new AjaxResult();
		User user = (User) SecurityUtils.getSubject().getPrincipal();

		if (ObjectUtil.isNull(user)) {
			result.setSuccess(false);
			result.setMsg("请登录");
			return result;
		}
		try {

			Func selectById = funcMapper.selectById(func.getFuncId());
			if (StrUtil.equals(selectById.getFuncLevel(), "1")) { //父菜单

				String[] childFuncId = new String[0];
				childFuncId = ArrayUtil.append(childFuncId, func.getFuncId());
				List<Func> childFuncList = funcMapper.selectList(new QueryWrapper<Func>().eq("pid", func.getFuncId()));
				for (Func childFunc : childFuncList) {
					childFuncId = ArrayUtil.append(childFuncId, childFunc.getFuncId());
				}

				int i = funcMapper.deleteBatchIds(Arrays.asList(childFuncId));
				if (i > 0) {
					result.setSuccess(true);
					result.setMsg("删除模块以及模块下所有菜单成功");
					funcTreeCache.clear();
					return result;
				}

			} else {


				int flag = funcMapper.deleteById(func.getFuncId());
				if (flag > 0) {
					result.setSuccess(true);
					result.setMsg("删除成功");
					funcTreeCache.clear();
					return result;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.setSuccess(false);
			result.setMsg("删除失败,失败信息为" + e.toString());
			return result;
		}

		return result;
	}

}
